package gdepot

import grails.converters.XML
import grails.transaction.Transactional

@Transactional
class TransactionService {

    // ---
    def generator = { String alphabet, int n ->
        new Random().with {
            (1..n).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
        }
    }

    def sendRequest(url,params) {
        URL _url = new URL(url)
        HttpURLConnection urlConnection = (HttpURLConnection)_url.openConnection()
        println _url
        urlConnection.setRequestMethod('POST')
        urlConnection.setDoOutput(true)
        urlConnection.setReadTimeout(6000)
        String requestParams='';
        params.each{
            if(!requestParams){
                requestParams += it.key +'='+ it.value
            }
            else{
                requestParams +='&' + it.key +'='+ it.value
            }
        }
        urlConnection.outputStream.withWriter {Writer writer -> writer.write requestParams}
        def responeResult = urlConnection.inputStream.withReader {Reader reader -> reader.text}
        return responeResult
    }

//代收接口 - 这块还可以再精简一下
    def payForCollection(accountBank, transactionRecord)
    {
        def version = TransactionRecordConfig.version
        def merdt = new Date().format('yyyyMMdd')
        def name = accountBank.fullName
        def bank = accountBank.bank
        def bankCode = bank.code
        def cardNo = accountBank.bankCardNo
        println " 传入的amount：" +transactionRecord.transactionAmount
        def amt = transactionRecord.transactionAmount*100 as Integer // 以分为单位
        println " 传给富友的amount：" + amt
        def entseq = ''
        def memo = ''
        def cellphone = accountBank.cellphone
        def certtp = '0'
        def certno = accountBank.idCard
        def orderCode = transactionRecord.orderSerialNumber

        def merchantNumber = TransactionRecordConfig.testmerchantId // 测试商户号

        def merchantPassword = TransactionRecordConfig.testPrivateKey//'123456' //(测试)商户密码

        def requestType = TransactionRecordConfig.payType//'sincomeforreq'  //请求类型
        def url =  TransactionRecordConfig.requestPayForServletofTesturl    //'http://www-1.fuiou.com:8992/fuMer/req.do'
        try {

            def xmlString = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><incomeforreq><ver>' + version + '</ver><merdt>' + merdt + '</merdt><orderno>' + orderCode + '</orderno><bankno>' + bankCode + '</bankno><accntno>' + cardNo + '</accntno><accntnm>' + name + '</accntnm><amt>' + amt + '</amt><entseq>' + entseq + '</entseq><memo>' + memo+ '</memo><mobile>' + cellphone +'</mobile><certtp>' + certtp + '</certtp><certno>' + certno + '</certno></incomeforreq>'

            def mac = merchantNumber  + '|' + merchantPassword + '|' + requestType + '|' + xmlString
            //def mac =URLEncoder.encode((merchantNumber  + '|' + merchantPassword + '|' + requestType + '|' + xmlString),"UTF-8");
            def requestParams = ['merid': merchantNumber, 'reqtype': requestType, 'xml': xmlString, 'mac': mac.encodeAsMD5()]
            println "requestParams:"+requestParams
            def resultStr = sendRequest(url, requestParams) //

            def xmlObject = new XmlParser().parseText(resultStr)
            def responseCode = xmlObject.ret.text()
            def  responseDescription = xmlObject.memo.text()

            println "responseCode:${responseCode},responseDescription:${responseDescription}"
            return [orderSerialNumber: orderCode, responseCode: responseCode, responseDescription: responseDescription]

        }
        catch (Exception e)
        {
            println "payForCollection:"+e.message
            //return [state:400,message:"程序内部错误！"] as JSON
            def returnMsg = "payForCollection:" + e.message
            return [orderSerialNumber: orderCode, responseCode: 400, responseDescription: returnMsg]
        }
    }

    // 5 快捷支付的五要素签约
    def sendFiveElementsQuickPay(name, bankCode, bankCardNo, certificateType, certificateNo, cellPhone)
    {

        def version = TransactionRecordConfig.version
        def srcChnl = 'DSF' // 代收付
        def busiCode = 'AC01' // 业务代码，默认为AC01
        def userName = name//jsonObject.name//'李翔'
        def acntTp = '01' // 借记卡
        //测试时的商户号
        def merchantCode = TransactionRecordConfig.testmerchantId //'0002900F0345178'//'290062110000031'
        println "merchantCode:"+merchantCode
        def isCallback = '0'  //
//        def reserved1 = '0' // 保留字段
        def signature = '' // 签名字段

        //证件类型的处理
        switch(certificateType)
        {
//        certificateType inList: ['0','1','2','3','5','7'],nullable: true
//        certificateType inList: [,'护照','军官证','士兵证','回乡证','户口本','外国护照','其他'
            case '身份证': certificateType = '0'
                 break
            case '护照': certificateType = '1'
                break
            case '军官证': certificateType = '2'
                break
            case '士兵证': certificateType = '3'
                break
            case '回乡证': certificateType = '4'
                break
            case '户口本': certificateType = '5'
                break
            case '外国护照': certificateType = '6'
                break
            case '其他': certificateType = '7'
                break

        }
        //userNm = URLEncoder.encode(userNm, "utf-8")
        def list = []
        list.add(srcChnl)
        list.add(busiCode)
        list.add(bankCode)
        list.add(userName)
        list.add(cellPhone)
        list.add(certificateType)
        list.add(certificateNo)
        list.add(acntTp)
        list.add(bankCardNo)
        list.add(merchantCode)
        list.add(isCallback)
//        list.add(reserved1)

        signature = dataSortAndSign(list)   // 数字签名
        println "signature:"+signature
        // 拼接xml
        try
        {

            String reqestXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><custmrBusi><srcChnl>" + srcChnl+ "</srcChnl><busiCd>" + busiCode + "</busiCd><bankCd>" + bankCode + "</bankCd><userNm>" + userName + "</userNm><mobileNo>" + cellPhone + "</mobileNo><credtTp>" + certificateType + "</credtTp><credtNo>" + certificateNo + "</credtNo><acntTp>"+ acntTp + "</acntTp><acntNo>"+ bankCardNo + "</acntNo><mchntCd>" + merchantCode + "</mchntCd><isCallback>" + isCallback + "</isCallback><reserved1>" + '' + "</reserved1><signature>"+ signature +"</signature></custmrBusi>"
            println "reqestXml:"+reqestXml

            //测试环境快捷支付五要素签约的地址
            def responseXml = sendRequest(TransactionRecordConfig.requestSignFiveElementsQuickServleofTesturl, [xml: URLEncoder.encode(reqestXml.toString(),"UTF-8")])
            println responseXml

            def resultStr = URLDecoder.decode(responseXml,"UTF-8")
            def xmlObject = XML.parse(resultStr)
            def responseCode = xmlObject.respCd
            def responseDescription = xmlObject.respDesc

            def returnMsg = "responseCode: " + responseCode + "#" + "responseDescription: " + responseDescription
            return [responseCode: responseCode, responseDescription: responseDescription]
        }
        catch(Exception e)
        {
            println "sendFiveElementsQuickPay()" + e.message
            //return [state: 400,message: "程序内部错误!"] as JSON
            def returnMsg = "sendFiveElementsQuickPay(): " + e.message
            return [responseCode: 400, responseDescription: returnMsg]
        }

    }
    // 代收付的手机验证码验证
    def sendVerifyCodeInQuickPay(verifyCode, bankCardNo)
    {
        def version = TransactionRecordConfig.version
        def merchantId = TransactionRecordConfig.testmerchantId     //测试商户号'0002900F0345178'
        def signature = ''

        def list = []
        list.add(bankCardNo)
        list.add(merchantId)
        list.add(verifyCode)

        signature = dataSortAndSign(list) // 数字签名
        println "signature:"+signature
        try
        {
            String reqestXml = '<?xml version="1.0" encoding="UTF-8"?><custmrBusi><acntNo>'
            + bankCardNo + '</acntNo><mchntCd>' + merchantId + '</mchntCd><verifyCode>'
            + verifyCode + '</verifyCode><signature>' + signature + '</signature></custmrBusi>'
            println "requst xml: " + reqestXml

            def url = TransactionRecordConfig.requstVerifyCodeInQuickPayServletofTesturl //测试环境地址

//            def responseXml = sendRequest(TransactionRecordConfig.requstVerifyCodeInQuickPayServleturl, [xml: URLEncoder.encode(reqestXml.toString(),"UTF-8")])
            def responseXml = sendRequest(TransactionRecordConfig.requstVerifyCodeInQuickPayServletofTesturl, [xml: URLEncoder.encode(reqestXml.toString(),"UTF-8")])

            def resultStr = URLDecoder.decode(responseXml,"UTF-8")
            println "resultStr: " + resultStr

            def xmlObject = XML.parse(resultStr)
            def responseCode = xmlObject.respCd
            def responseDescription = xmlObject.respDesc

            def returnMsg = "responseCode: " + responseCode + "responseDescription: " + responseDescription
            return [responseCode: responseCode, responseDescription: responseDescription]
        }
        catch (Exception e)
        {
            println "sendVerifyCodeInQuickPay()" + e.message
            //return [state: 400,message: "程序内部错误!"] as JSON
            def returnMsg = "sendVerifyCodeInQuickPay(): " + e.message
            return [responseCode: 400, responseDescription: returnMsg]
        }

    }
    // 代收付中验卡和开户数字签名数据排序
    def dataSortAndSign(list)
    {
        def signValue = ''
        String[] strs = new String[list.size()];
        for(int i = 0; i < strs.length; i++)
        {
            strs[i] = list.get(i);
        }
        println "strs: " + strs
        Arrays.sort(strs);
        for(int i = 0; i < strs.length; i++)
        {
            signValue = signValue + strs[i] + '|'
        }
        signValue = signValue.substring(0, signValue.length() - 1)
        def sign = signValue.encodeAsSHA1()

        sign =  sign + '|' + TransactionRecordConfig.testPrivateKey  // TransactionRecordConfig.privateKey 测试环境秘钥
        def signature = sign.encodeAsSHA1()
        return signature
    }

}
